<template>
  <div class="flexContent">
    <div class="searchBox">
      <el-form ref="formRef" :model="sForm" class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品">
                  <el-input v-clearEmoji v-model.trim="sForm.mnemonic" size="small" clearable style="width: 95%"
                    placeholder="请输入助记符/名称/条码" @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="品牌" prop="brandId">
                  <el-select @click.native="getBrand" v-model="sForm.brandId" popper-class="eloption" clearable
                    style="width: 95%" filterable placeholder="请选择品牌">
                    <el-option v-for="brand in brandList" :key="brand.id" :value="brand.id" :label="brand.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品状态">
                  <el-select v-model="sForm.productState" style="width: 95%" clearable placeholder="请选择商品状态">
                    <el-option value="0" label="正常" />
                    <el-option value="1" label="停用" />
                    <el-option value="2" label="淘汰" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="点采状态">
                  <el-select v-model="sForm.isPick" style="width: 95%" clearable placeholder="请选择点采状态">
                    <el-option value="1" label="允许点采" />
                    <el-option value="0" label="禁止点采" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品分类">
                  <!-- @focus="getCategoryTreeList" -->
                  <el-cascader ref="cascaderRef" v-model.trim="sForm.categoryId" placeholder="请选择商品分类" clearable
                    :props="defaultProps" :options="categoryList" style="width: 95%" filterable @change="handleChange" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="单位">
                  <el-select v-model="sForm.unitId" @click.native="getUnitEasy" clearable placeholder="请选择单位"
                    popper-class="eloption" style="width: 95%" filterable>
                    <el-option v-for="unit in unitList" :key="unit.id" :value="unit.id" :label="unit.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="供应商">
                  <el-select v-model="sForm.supplierId" popper-class="eloption" clearable style="width: 95%" filterable
                    placeholder="请选择供应商">
                    <el-option v-for="item in firstSupplierList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetForm" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" v-has="'goods_add'" @click="addFn">新增</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" class="tablebox" border ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          align="center">
          <vxe-column type="seq" title="序号" width="80"></vxe-column>
          <vxe-column field="firstCode" min-width="180" title="商品条码" />
          <vxe-column field="itemCode" title="商品编号" min-width="180" />
          <vxe-column field="agreedPrice" min-width="150" title="协议进价（元）" />
          <vxe-column :min-width="elTableAdaptationWidth('name', goodsList)" title="商品名称">
            <template v-slot="{ row }">
              <span style=" color: rgb(0, 42, 255)" @click.stop="detail(row)">
                {{ row.name }}</span>
            </template>
          </vxe-column>
          <vxe-column field="outboundPrice" min-width="140" title="出仓价（元）" />
          <vxe-column field="categroyName" :min-width="elTableAdaptationWidth('categroyName', goodsList)" title="商品分类" />
          <vxe-column field="standard" min-width="100" title="规格" />
          <vxe-column field="unitName" width="80" title="单位" />
          <vxe-column field="brandName" title="品牌" :min-width="elTableAdaptationWidth('brandName', goodsList)" />
          <vxe-column field="producer" title="产地" :min-width="elTableAdaptationWidth('producer', goodsList)" />
          <vxe-column field="bigPacking" min-width="120" title="大包装" />
          <vxe-column field="supplierName" title="默认供应商"
            :min-width="elTableAdaptationWidth('supplierName', goodsList) + 20" />
          <vxe-column field="type" min-width="120" title="商品类型">
            <template v-slot="{ row }">
              <span>{{ row.type === "0" ? "整件商品" : "拆零商品" }}</span>
            </template>
          </vxe-column>
          <vxe-column min-width="150" title="更新日期">
            <template v-slot="{ row }">
              {{ row.updateTime ? row.updateTime : row.createTime | parseTime }}
            </template>
          </vxe-column>
          <vxe-column min-width="100" title="商品状态">
            <template v-slot="{ row }">
              <el-tag v-if="row.productState === '0'" type="success" size="small">正常</el-tag>
              <el-tag v-if="row.productState === '1'" type="info" size="small">停用</el-tag>
              <el-tag v-if="row.productState === '2'" type="danger" size="small">淘汰</el-tag>
            </template>
          </vxe-column>
          <vxe-column min-width="100" title="点采状态">
            <template v-slot="{ row }">
              <el-tag v-if="row.isPick === '1'" type="success" size="small">允许点采</el-tag>
              <el-tag v-if="row.isPick === '0'" type="info" size="small">禁止点采</el-tag>
            </template>
          </vxe-column>
          <vxe-column v-if="$showFn(['goods_edit', 'goods_detail', 'goods_delete', 'update_price'])" fixed="right"
            width="200" title="操作">
            <template v-slot="{ row }">
              <el-button type="text" v-has="'goods_edit'" @click.stop="edit(row)">修改</el-button>
              <el-button type="text" style="margin-right: 5px" @click.stop="detail(row)"
                v-has="'goods_detail'">详情</el-button>
              <el-button type="text" v-has="'goods_delete'" v-if="row.productState === '2'" style="color: red"
                @click="$delFn('商品', del, row)">删除</el-button>
              <el-button type="text" v-has="'update_price'" style="color: rgb(162, 0, 255)(255, 0, 157)"
                @click="updatePrice(row)">改价</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog title="调价" :visible.sync="dialogFormVisible" width="30%" @close="closeDialog">
      <el-form :model="priceForm" :rules="goodsRules" ref="priceForm" label-width="120px">
        <!-- <el-form-item label="价格类型">
          <el-select v-model="priceForm.type" placeholder="请选择类型">
            <el-option label="协议进价(元)" value="0"></el-option>
            <el-option label="出仓价(元)" value="1"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="协议进价(元)" prop="agreedPrice">
          <el-input v-model="priceForm.agreedPrice" placeholder="请输入协议进价"></el-input>
          <el-button type="primary" @click="updateagreedPrice" style="margin-left: 20px;">确 定</el-button>
        </el-form-item>
        <el-form-item label="出仓价(元)" prop="outboundPrice">
          <el-input v-model="priceForm.outboundPrice" placeholder="请输入出仓价"></el-input>
          <el-button type="primary" @click="updateGoodsoutboundPrice" style="margin-left: 20px;">确 定</el-button>
        </el-form-item>
      </el-form>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateGoodsPrice">关 闭</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { getSCMList } from "@/api/scm";
import {
  getGoodsList,
  delGoods,
  getUnitEasy,
  getCategoryTreeList,
  getBrandEasy,
  updateGoodsPrice
} from "@/api/goods";
export default {
  name: "GoodsInfo",
  data() {
    return {
      sForm: {
        mnemonic: "",
        brandId: "",
        categoryId: "",
        unitId: "",
        productState: "",
        supplierId: '',
        isPick: ''
      },
      isSearch: false,
      brandList: [],
      goodsList: [],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      categoryList: [], // 商品分类列表
      categoryId: "",
      defaultProps: {
        children: "children",
        label: "name",
        emitPath: false,
        value: "id",
        // checkStrictly: true,
      },
      unitList: [], // 单位列表
      firstSupplierList: [],
      selectedRow: {},
      dialogFormVisible: false,
      priceForm: {
        type: '0',
        agreedPrice: '',
        outboundPrice: ''
      },
      goodsRules: {
        agreedPrice: [
          {
            pattern:
              /^(([1-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
            message: "协议进价必须大于0",
            trigger: "change",
          },
          {
            required: "true",
            message: "协议进价不能为空",
            trigger: "change",
          },
          {
            min: 0,
            max: 15,
            message: "协议进价不能超过10位数",
            trigger: "change",
          },
          // {
          //   // message: "协议进价不能大于出仓价",
          //   trigger: "change",
          //   validator: (rule, value, callback) => {
          //     if (this.priceForm.outboundPrice <= value) {
          //       callback(new Error('协议进价不能大于等于出仓价'));
          //     } else {
          //       callback();
          //     }
          //   },
          // }
        ],
        outboundPrice: [
          {
            pattern:
              /^(([1-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
            message: "出仓价必须大于0",
            trigger: "change",
          },
          {
            required: "true",
            message: "出仓价不能为空",
            trigger: "change",
          },
          {
            min: 0,
            max: 15,
            message: "出仓价不能超过10位数",
            trigger: "change",
          },
          // {
          //   // message: "协议进价不能大于出仓价",
          //   trigger: "change",
          //   validator: (rule, value, callback) => {
          //     if (this.priceForm.agreedPrice >= value) {
          //       callback(new Error('协议进价不能大于等于出仓价'));
          //     } else {
          //       callback();
          //     }
          //   },
          // }
        ],
      }
    };
  },
  computed: {},
  created() {
    this.getGoodsList();
    // this.getUnitEasy();
    this.getCategoryTreeList();
    // this.getBrand();
    this.getSCMList();
  },
  methods: {
    async getSCMList() {
      const res = await getSCMList();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data.list;
      }
    },
    async getBrand() {
      const res = await getBrandEasy();
      if (res.code === 200) {
        const data = res.data;
        this.brandList = data.brandList;
        console.log(data);
        console.log("品牌", this.brandList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getUnitEasy() {
      const res = await getUnitEasy();
      if (res.code === 200) {
        const data = res.data;
        this.unitList = data.unitList;
        // console.log(data)
        console.log("单位", this.unitList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getCategoryTreeList() {
      const res = await getCategoryTreeList();
      if (res.code === 200) {
        this.categoryList = res.data.categoryList;
        console.log("categoryList", this.categoryList);
      }
      // console.log(res)
    },
    addFn() {
      this.$router.push({
        path: "goodsAdd",
        query: {
          type: "add",
        },
      });
    },
    async getGoodsList() {
      if (!this.isSearch) {
        this.sForm = {
          mnemonic: "",
          brandId: "",
          categoryId: "",
          unitId: "",
          productState: "",
          supplierId: '',
          isPick: ''
        };
      }
      const res = await getGoodsList({ ...this.page, ...this.sForm });
      if (res.code === 200) {
        const result = res.data;
        this.goodsList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        const $table = this.$refs.xTable1
        $table.loadData(this.goodsList);
        console.log("goodList", this.goodsList);
      } else {
        // this.$message.error(res.message);
      }
      // console.log(res)
    },
    edit(row) {
      this.$router.push({
        path: "goodsEdit",
        query: {
          type: "edit",
          id: row.id,
        },
      });
    },
    detail(row) {
      this.$router.push({
        path: "goodsDetail",
        query: {
          type: "detail",
          id: row.id,
        },
      });
    },
    async del(row) {
      // console.log(row)
      const res = await delGoods({ id: row.id });
      if (res.code === 200) {
        this.$message.success(res.message);
        this.getGoodsList();
      } else {
        // this.$message.error(res.message);
      }
      // console.log(res)
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getGoodsList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getGoodsList();
    },
    // 分类选择后
    handleChange(value) {
      console.log("分类", value);
      const nodes = this.$refs.cascaderRef.getCheckedNodes();
      console.log("nodes", nodes);
      this.sForm.categoryId = value;
    },
    resetForm() {
      // 重置
      this.isSearch = false;
      console.log("reset", this.$refs.formRef);
      this.$refs.formRef.resetFields();
      this.sForm = {
        mnemonic: "",
        brand: "",
        categoryId: "",
        unitId: "",
        productState: "",
        supplierId: '',
        isPick: ''
      };
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.getGoodsList();
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.getGoodsList();
    },
    updatePrice(row) {
      this.selectedRow = row
      this.$set(this.priceForm, 'agreedPrice', String(row.agreedPrice))
      this.$set(this.priceForm, 'outboundPrice', String(row.outboundPrice))
      this.dialogFormVisible = true
      // this.$refs.priceForm.resetFields()
    },
    closeDialog() {
      this.$refs.priceForm.resetFields()
      this.dialogFormVisible = false
    },
    async updateagreedPrice() {
      this.priceForm.type = '0'
      this.$refs.priceForm.validate(async (isOk) => {
        if (isOk) {
          let newPrice = ''
          if (this.priceForm.type == '0') {
            newPrice = this.priceForm.agreedPrice
            if (newPrice >= this.selectedRow.outboundPrice) {
              this.$confirm(`当前协议进价大于出仓价, 确认修改吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(async () => {
                  const res = await updateGoodsPrice({
                    newPrice,
                    priceType: this.priceForm.type,
                    commodityId: this.selectedRow.id
                  })
                  if (res.code === 200) {
                    this.$message.success(res.message)
                    this.$set(this.selectedRow, 'agreedPrice', String(newPrice))
                    // this.closeDialog()
                    this.getGoodsList()
                  }
                })
                .catch(() => { });
            } else {
              const res = await updateGoodsPrice({
                newPrice,
                priceType: this.priceForm.type,
                commodityId: this.selectedRow.id
              })
              if (res.code === 200) {
                this.$message.success(res.message)
                this.$set(this.selectedRow, 'agreedPrice', String(newPrice))
                // this.closeDialog()
                this.getGoodsList()
              }
            }
          }
        }
      })
    },
    async updateGoodsoutboundPrice(type) {
      this.priceForm.type = '1'
      this.$refs.priceForm.validate(async (isOk) => {
        if (isOk) {
          let newPrice = ''
          console.log('1111');
          newPrice = this.priceForm.outboundPrice
          if (newPrice <= this.selectedRow.agreedPrice) {
            this.$confirm(`当前出仓价小于协议进价, 确认修改吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(async () => {
                const res = await updateGoodsPrice({
                  newPrice,
                  priceType: this.priceForm.type,
                  commodityId: this.selectedRow.id
                })
                if (res.code === 200) {
                  this.$message.success(res.message)
                  this.$set(this.selectedRow, 'outboundPrice', String(newPrice))
                  // this.closeDialog()
                  this.getGoodsList()
                }
              })
              .catch(() => { });
          } else {
            const res = await updateGoodsPrice({
              newPrice,
              priceType: this.priceForm.type,
              commodityId: this.selectedRow.id
            })
            if (res.code === 200) {
              this.$message.success(res.message)
              // this.closeDialog()
              this.$set(this.selectedRow, 'outboundPrice', String(newPrice))
              this.getGoodsList()
            }
          }

          // if()
        }
      })
    }
  },

  activated() {
    this.isSearch = true
    this.getGoodsList();
    // this.getUnitEasy();
    this.getCategoryTreeList();
    // this.getBrand();
    this.getSCMList();
  }
};
</script>

<style lang="scss" scoped></style>
